package com.huika.renrench.control.my.activity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.huika.lib.bitmap.core.DisplayImageOptions;
import com.huika.lib.bitmap.core.ImageLoader;
import com.huika.lib.bitmap.core.ImageLoaderConfiguration;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.lib.utils.MoneyShowTool;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.my.bank.activity.BankInfoActivity;
import com.huika.renrench.control.my.bank.activity.MyBankCardActivity;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.AccountPropertyBean;
import com.huika.renrench.support.bean.BankCardBean;
import com.huika.renrench.support.bean.LianLianBean;
import com.huika.renrench.support.bean.WithDrawBean;
import com.huika.renrench.view.TitleBarHelper;

/**
 * 
 * @description：提现
 * @author zc
 * @date 2015年6月2日 上午11:56:31
 */
public class WithDrawActivity extends BaseAct implements Listener<RequestResult<ArrayList<BankCardBean>>> {

	private View layout1;
	private ImageView bank_logo;
	private TextView bank_name;
	private TextView last_no;
	private TextView can_withdraw_money_detail;
	private TextView free_withdraw_money_detail;
	private EditText input_withdraw_money_detail;
	
	/** 取消显示 提现费用  by wuwenfeng  **/
	//private TextView withdraw_expense_detail;
	
	private TextView pay_password_detail;
	private Button confirm;
	private TextView prompt;
	private String userId;
	private BankCardBean bankCardBean;
	private DisplayImageOptions options;
	private TextView prompt_detail;
	private Dialog dialog;
	private boolean isFresh;
	private double withDrawRate;
	private int withDrawFday;
	private double freeWithDrawMount;
	private double banlance;
	private double investAmount;
	private TextView free_withdraw_money_detail_prompt;
	private View free_withdraw_money_layout;
	
	/**
	 * 可提现金额   (2015-10-23 by wuwenfeng)
	 */
	private TextView withdraw_noForbit;
	
	@Override
	protected void initWidget() {
		super.initWidget();
		layout1 = findViewById(R.id.layout1);
		bank_logo = (ImageView) findViewById(R.id.bank_logo);
		bank_name = (TextView) findViewById(R.id.bank_name);
		last_no = (TextView) findViewById(R.id.last_no);
		can_withdraw_money_detail = (TextView) findViewById(R.id.can_withdraw_money_detail);
		input_withdraw_money_detail = (EditText) findViewById(R.id.input_withdraw_money_detail);
		/** 取消显示 提现费用  by wuwenfeng  **/
		//withdraw_expense_detail = (TextView) findViewById(R.id.withdraw_expense_detail);
		pay_password_detail = (TextView) findViewById(R.id.pay_password_detail);
		withdraw_noForbit = (TextView) findViewById(R.id.withdraw_noForbit);
		confirm = (Button) findViewById(R.id.confirm);
		prompt = (TextView) findViewById(R.id.prompt);
		prompt_detail = (TextView) findViewById(R.id.prompt_detail);
		free_withdraw_money_detail = (TextView) findViewById(R.id.free_withdraw_money_detail);
		free_withdraw_money_detail_prompt = (TextView) findViewById(R.id.free_withdraw_money_detail_prompt);
		free_withdraw_money_layout = findViewById(R.id.free_withdraw_money_layout);
		
//		confirm.setOnClickListener(this);
//		layout1.setOnClickListener(this);
		input_withdraw_money_detail.addTextChangedListener(new MyWatcher());
		getMyBankCardList(userId, 1, 1);
		getTip(userId);
		getDataFromNet(userId);
	} 
	
	private void getDataFromNet(String userId) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		FormResultRequest<AccountPropertyBean> getResultRequest = new FormResultRequest<AccountPropertyBean>(
				UrlConstants.GETUSERTOTALAMOUNT, new Listener<RequestResult<AccountPropertyBean>>() {

					@Override
					public void onResponse(RequestResult<AccountPropertyBean> account) {
						dismissLoadingDialog();
						if(account.flag == 1) {
							withDrawRate = account.getRs().withDrawRate;
							withDrawFday = account.getRs().withDrawFday;
							freeWithDrawMount = account.getRs().freeWithDrawMount;
							investAmount = account.getRs().investAmount;
							banlance = GlobalApp.getInstance().getUseBalance(account.getRs().rechargeAmount, 
									account.getRs().withdrawAmount, account.getRs().investRevenue, 
									account.getRs().frozenBalance, account.getRs().investAmount, account.getRs().revenueFeeAmount);
//							can_withdraw_money_detail.setText(Html.fromHtml("<font color=#fe8900>" + (MoneyShowTool.twolastDF(banlance)) + "</font>" + "元"));
							can_withdraw_money_detail.setText(Html.fromHtml(MoneyShowTool.twolastDF(banlance)) + "元");
							free_withdraw_money_detail.setText(MoneyShowTool.twolastDF(freeWithDrawMount) + "元");
							
							/** 可提现金额  (2015-10-23 by wuwenfeng)**/
							withdraw_noForbit.setText(MoneyShowTool.twolastDF(account.getRs().noForbitWithDrawMount) + "元");
							
							if(subtract(banlance, freeWithDrawMount) < 0) {
								free_withdraw_money_detail_prompt.setVisibility(View.VISIBLE);
							}
							if(account.getRs().withDrawRate != 0) {
								free_withdraw_money_layout.setVisibility(View.VISIBLE);
							} else {
								free_withdraw_money_layout.setVisibility(View.GONE);
							}
						}
					}
				}, this,
				new TypeToken<RequestResult<AccountPropertyBean>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);
	}
	
	private double add(double numberA, double numberB) {
		BigDecimal bigDecimalA = new BigDecimal(numberA);
		BigDecimal bigDecimalB = new BigDecimal(numberB);
		return bigDecimalA.add(bigDecimalB).doubleValue();
	}
	
	private double subtract(double numberA, double numberB) {
		BigDecimal bigDecimalA = new BigDecimal(numberA);
		BigDecimal bigDecimalB = new BigDecimal(numberB);
		return bigDecimalA.subtract(bigDecimalB).doubleValue();
	}
	
	private double multiply(double numberA, double numberB) {
		BigDecimal bigDecimalA = new BigDecimal(numberA);
		BigDecimal bigDecimalB = new BigDecimal(numberB);
		return bigDecimalA.multiply(bigDecimalB).doubleValue();
	}
	
	private void warning() {
		dialog = MMAlert.createShowCenterDialog(context, "温馨提示", "您还没绑定银行卡，请前往绑定", "忽略", "立即前往", new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		}, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showActivity(WithDrawActivity.this, MyBankCardActivity.class);
			}
		});
		dialog.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(DialogInterface dialog) {
				if(!isFresh) {
					finish();
				}
			}
		});
		dialog.show();
	}
	
	private void accountWithdraw(String userId, String mount, String bankId, String password) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("mount", mount);
		ajaxParams.putCommonTypeParam("bankId", bankId);
		ajaxParams.putCommonTypeParam("password", MD5Security.getMd5_32_UP(password));
		FormResultRequest<WithDrawBean> request = new FormResultRequest<WithDrawBean>(UrlConstants.ACCOUNTWITHDRAW, new Listener<RequestResult<WithDrawBean>>() {

			@Override
			public void onResponse(RequestResult<WithDrawBean> arg0) {
				dismissLoadingDialog();
				if(arg0.flag == 1) {
					if(arg0.getRs().key == -1) {
						Intent intent = new Intent(WithDrawActivity.this, WithdrawSuActivity.class);
						intent.putExtra("withdrawBean", arg0.getRs());
						showActivity(WithDrawActivity.this, intent);
						finish();
					}
				}
				ToastMsg.showToastMsg(WithDrawActivity.this, arg0.msg);
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError arg0) {
				arg0.printStackTrace();
			}
		}, new TypeToken<RequestResult<WithDrawBean>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch(v.getId()) {
			case R.id.confirm:
				checkInput();
				break;
			case R.id.layout1:
				if(bankCardBean != null) {
					Intent intent = new Intent(this, BankInfoActivity.class);
					intent.putExtra("bankCardBean", bankCardBean);
					intent.putExtra("flag", 1);
					startActivityForResult(intent, 100);
				} else {
					ToastMsg.showToastMsg(this, "网络不稳定，请稍后再试!");
				}
				break;
		}
	}
	
	private void getTip(String userId) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("tipType", "fillMoney");
		FormResultRequest<Object> getResultRequest = new FormResultRequest<Object>(
				UrlConstants.GETTIP, new Listener<RequestResult<Object>>() {

					@Override
					public void onResponse(RequestResult<Object> arg0) {
						dismissLoadingDialog();
						prompt.setVisibility(View.VISIBLE);
						prompt_detail.setText(Html.fromHtml(arg0.msg));
					}
				}, this,
				new TypeToken<RequestResult<AccountPropertyBean>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);
	}
	
	class MyWatcher implements TextWatcher {
		String tempStr;
		
		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			tempStr = s.toString();
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(!checkInputMoney(s.toString())) {
				input_withdraw_money_detail.setText(tempStr);
				input_withdraw_money_detail.setSelection(input_withdraw_money_detail.length());
				return;
			} else if(s.length() > 1 && s.toString().substring(0, 1).equals("0") && !s.toString().startsWith("0.")) {
				input_withdraw_money_detail.setText(s.toString().substring(1));
				input_withdraw_money_detail.setSelection(input_withdraw_money_detail.length());
			} else if(!s.toString().endsWith(".") && !s.toString().equals("")) {
				double inputD = Double.parseDouble(s.toString());
//				double freeAmount = subtract(add(banlance, investAmount), recentChargeMount);
//				if(freeAmount <= 0d) {
//					withdraw_expense_detail.setText(MoneyShowTool.twolastDF(multiply(inputD, withDrawRate)) + "元");
//				} else if(subtract(freeAmount, inputD) < 0d){
//					withdraw_expense_detail.setText(MoneyShowTool.twolastDF(multiply(subtract(inputD, freeAmount), withDrawRate)) + "元");
//				}
				/** 取消显示 提现费用  by wuwenfeng  **/
				/*if(subtract(freeWithDrawMount, inputD) < 0d) {
					withdraw_expense_detail.setText(MoneyShowTool.twolastDF(multiply(subtract(inputD, freeWithDrawMount), withDrawRate), false) + "元");
				} else {
					withdraw_expense_detail.setText("0.00元");
				}*/
			}
		}
	}
	
	private boolean checkInputMoney(String money) {
		String patten = "^[0-9]{0,8}+(([.]{1})+([0-9]{0,2}))?$";
		return money.equals("")?true:money.matches(patten);
	}
	/**
	 * 
	 * @description：判断是否可以提交的金额
	 * @author zc
	 * @date 2015年6月23日 下午3:11:14
	 */
	private boolean canSubmitMoney(String money) {
		String patten = "^[0-9]+(.[0-9]{1,2})?$";
		return money.matches(patten);
	}
	
	private void checkInput() {
		if(input_withdraw_money_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入提现金额");
			return;
		} else if(!canSubmitMoney(input_withdraw_money_detail.getText().toString())) {
			ToastMsg.showToastMsg(this, "您输入的格式不正确，请重新输入");
			input_withdraw_money_detail.setText("");
			return;
		} 
		
		else if(Double.parseDouble(input_withdraw_money_detail.getText().toString()) > Double.parseDouble(can_withdraw_money_detail.getText().toString().substring(0, can_withdraw_money_detail.length() - 1))) {
			ToastMsg.showToastMsg(this, "您投资的金额超过您的可提金额");
			return;
		}  else if(GlobalApp.userModel.getIsSetPayPwd() == 0) {
			ToastMsg.showToastMsg(this, "您没有设置交易密码，请前往设置后再提现");
			return;
		} else if(pay_password_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入交易密码");
			return;
		}
		if(bankCardBean != null) {
			
			accountWithdraw(userId, input_withdraw_money_detail.getText().toString(), bankCardBean.getCardId(), pay_password_detail.getText().toString());
		} else {
			ToastMsg.showToastMsg(this, "网络不稳定，请稍后再试!");
		}
		
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		getMyBankCardList(userId, 1, 1);
	}

	@Override
	protected void initData() {
		super.initData();
		TitleBarHelper barHelper = new TitleBarHelper(this, -1);
		barHelper.setTitleMsg("提现");
		barHelper.setLeftMsg("我的");
		userId = GlobalApp.userModel.getUserId();
		
		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.icon_default_small)
				// resource or drawable
						.showImageForEmptyUri(R.drawable.icon_default_small).showImageOnFail(R.drawable.icon_default_small).cacheInMemory(true)// 开启内存缓存
						.cacheOnDisk(true) // 开启硬盘缓存
						.resetViewBeforeLoading(true).build();
	}
	
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_withdraw);
	}
	
	/**
	 * 
	 * @description：获取我的银行卡列表
	 * @author zc
	 * @date 2015年6月2日 下午5:44:17
	 */
	private void getMyBankCardList(String userId, int pageNo, int pageSize) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("pageNo", pageNo);
		ajaxParams.putCommonTypeParam("pageSize", pageSize);
		FormResultRequest<ArrayList<BankCardBean>> request = new FormResultRequest<ArrayList<BankCardBean>>(UrlConstants.GETMYBANKCARDLIST, this, this, new TypeToken<RequestResult<ArrayList<BankCardBean>>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	@Override
	public void onResponse(RequestResult<ArrayList<BankCardBean>> arg0) {
		dismissLoadingDialog();
		if(arg0.flag == 1) {
			if(arg0.getRs().size() > 0) {
				isFresh = true;
				bankCardBean = arg0.getRs().get(0);
				ImageLoader imageLoader = ImageLoader.getInstance();
				imageLoader.init(ImageLoaderConfiguration.createDefault(this));
				bankCardBean = arg0.getRs().get(0);
				imageLoader.displayImage(bankCardBean.getLogoImg(), bank_logo, options);
				bank_name.setText(bankCardBean.getBankName());
				last_no.setText("尾号" + bankCardBean.getCardNumber().substring(bankCardBean.getCardNumber().length() - 4));
				confirm.setOnClickListener(this);
				layout1.setOnClickListener(this);
			} else {
				warning();
			}
		}
	}

}
